/*
 * @copyright fxsen <br/>
 * @date 2022/4/24 19:14 <br/>
 * @email <a href="mailto:fxsen@foxmail.com">
 * @author fxsen
 */
package com.fxsen.commons.sysmanager.core.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.fxsen.commons.core.base.common.service.impl.CommonServiceImpl;
import com.fxsen.commons.core.properties.FileProperties;
import com.fxsen.commons.sysmanager.core.entity.LocalStorage;
import com.fxsen.commons.sysmanager.core.mapper.LocalStorageMapper;
import com.fxsen.commons.sysmanager.core.service.ILocalStorageService;
import com.fxsen.commons.utils.FileUtils;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.Collection;
import java.util.Date;
import java.util.List;

/**
 * 本地存储管理
 * @author fxsen
 * @date 2022/4/24 19:14
 * @email <a href="mailto:fxsen@foxmail.com">
 */
@Service
public class LocalStorageServiceImpl extends CommonServiceImpl<LocalStorageMapper,LocalStorage> implements ILocalStorageService {
    @Autowired
    private FileProperties properties;

    @Autowired
    private LocalStorageMapper localStorageMapper;

    @Override
    public LocalStorage create(String name, MultipartFile multipartFile) {
        FileUtils.checkSize(properties.getMaxSize(), multipartFile.getSize());
        String suffix = FileUtils.getExtensionName(multipartFile.getOriginalFilename());
        String type = FileUtils.getType(FileUtils.getFileType(suffix));
        String yyyyMMdd = DateUtil.format(new Date(), "yyyyMMdd");
        String filePath = properties.getPath().getPath()+yyyyMMdd+File.separator+type+File.separator;
        File file = FileUtils.upload(multipartFile, filePath);
        if(ObjectUtil.isNull(file)){
            throw new RuntimeException("文件上传失败");
        }
        try {
            String viewPath = file.getPath().replace(properties.getPath().getPath(),properties.getViewBaseUrl()+"file/").replace(File.separator,"/");
            name = StringUtils.isBlank(name) ? FileUtils.getFileNameNoEx(multipartFile.getOriginalFilename()) : name;
            LocalStorage localStorage = new LocalStorage(file.getName(),name,suffix,file.getPath(),
                    viewPath,type,FileUtils.getSize(multipartFile.getSize()));
            boolean save = save(localStorage);
            return save ? localStorage : null;
        }catch (Exception e){
            FileUtils.del(file);
            throw e;
        }
    }

    @Override
    public List<LocalStorage> getByOwnerIdAndOwnerCategory(String ownerId, String ownerCategory) {
        LambdaQueryWrapper<LocalStorage> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(LocalStorage::getOwnerId,ownerId);
        queryWrapper.eq(LocalStorage::getOwnerCategory,ownerCategory);
        return localStorageMapper.selectList(queryWrapper);
    }

    @Override
    public void delete(String id) {
        LocalStorage localStorage = localStorageMapper.selectById(id);
        if (localStorage != null) {
            int delete = localStorageMapper.deleteById(id);
            if (delete > 0 && StringUtils.isNotBlank(localStorage.getPath())){
                File file = new File(localStorage.getPath());
                if (file.exists()){
                    FileUtils.del(file);
                }
            }
        }
    }

    @Override
    public void delete(Collection<LocalStorage> idList) {
        List<LocalStorage> localStorages = localStorageMapper.selectBatchIds(idList);
        int batchIds = 0;
        if (CollectionUtils.isNotEmpty(localStorages)){
            batchIds = localStorageMapper.deleteBatchIds(localStorages);
        }
        if (batchIds > 0){
            for (LocalStorage localStorage : localStorages) {
                if (StringUtils.isNotBlank(localStorage.getPath())){
                    File file = new File(localStorage.getPath());
                    if (file.exists()){
                        FileUtils.del(file);
                    }
                }
            }
        }
    }

    @Override
    public void deleteByOwnerIdAndOwnerCategory(String ownerId, String ownerCategory) {
        List<LocalStorage> localStorageList = this.getByOwnerIdAndOwnerCategory(ownerId, ownerCategory);
        if (CollectionUtils.isNotEmpty(localStorageList)){
            localStorageMapper.deleteBatchIds(localStorageList);
        }
    }
}
